"""
服务管理路由
"""
from flask import Blueprint, request
from flask_jwt_extended import jwt_required
from utils import ApiResponse
from services.service_service import ServiceService

api_bp = Blueprint('service', __name__, url_prefix='/admin')
service_service = ServiceService()


@api_bp.route('/services', methods=['GET'])
@jwt_required()
def get_services():
    """获取服务列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        name = request.args.get('name', '').strip()
        type_id = request.args.get('type_id', type=int)
        
        data = service_service.get_services_paginated_dto(
            page=page,
            per_page=per_page,
            name=name,
            type_id=type_id
        )
        
        return ApiResponse.success(data=data)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/services/<int:service_id>', methods=['GET'])
@jwt_required()
def get_service(service_id):
    """获取服务详情"""
    try:
        data = service_service.get_service_dto(service_id)
        if not data:
            return ApiResponse.error(msg='服务不存在', code=404)
        
        return ApiResponse.success(data=data)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/services', methods=['POST'])
@jwt_required()
def create_service():
    """创建服务"""
    try:
        data = request.get_json()
        
        required_fields = ['name', 'price']
        for field in required_fields:
            if field not in data or not data[field]:
                return ApiResponse.error(msg=f'缺少必填字段: {field}', code=400)
        
        result = service_service.create_service_dto(
            name=data['name'],
            price=data['price'],
            description=data.get('description'),
            type_id=data.get('typeId')
        )
        
        return ApiResponse.success(data=result, msg='服务创建成功', code=201)
    except ValueError as e:
        return ApiResponse.error(msg=str(e), code=400)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/services/<int:service_id>', methods=['PUT'])
@jwt_required()
def update_service(service_id):
    """更新服务"""
    try:
        data = request.get_json() or {}
        
        update_data = {}
        field_mapping = {
            'name': 'name',
            'price': 'price',
            'description': 'description',
            'typeId': 'type_id'
        }
        
        for api_field, model_field in field_mapping.items():
            if api_field in data and data[api_field] is not None:
                update_data[model_field] = data[api_field]
        
        result = service_service.update_service_dto(service_id, **update_data)
        if not result:
            return ApiResponse.error(msg='服务不存在', code=404)
        
        return ApiResponse.success(data=result, msg='服务更新成功')
    except ValueError as e:
        return ApiResponse.error(msg=str(e), code=400)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/services/<int:service_id>', methods=['DELETE'])
@jwt_required()
def delete_service(service_id):
    """删除服务"""
    try:
        result = service_service.delete_service(service_id)
        if not result:
            return ApiResponse.error(msg='服务不存在', code=404)
        
        return ApiResponse.success(msg='服务删除成功')
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)


@api_bp.route('/service-types', methods=['GET'])
@jwt_required()
def get_service_types():
    """获取服务类型"""
    try:
        data = service_service.get_service_types_dto()
        return ApiResponse.success(data=data)
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)

